package client.popups.wizard;

/**
 * WizardGUI
 * @author patrickh
 */

import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.List;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

import miscellaneous.Storage;
import miscellaneous.TimeSupport;

import data.Appointment;
import data.Meeting;
import data.User;
import data.room.Reservation;
import data.room.Room;

public class AppointmentWizard extends JFrame{
    
	//a panel that uses CardLayout
	private JPanel cards; 
	
	// Card names
	final static String START = "1";
	final static String INFO = "2";
    final static String PARTICIPANTS = "3";
    final static String ROOM = "4";
    
    // Attributes for buttonPanel
    private JButton backButton;
    private JButton nextButton;
    private JButton cancelButton;
	
	//Keeps track for current card
	private int currentCard = 1;
	private boolean isMeeting = false;
	
	//All panels
	private AppointmentLocationDescription locationPicker;
	private AppointmentsRoomDescription roomPicker;
    private AppointmentInfoWizard infoPanel;
    private MeetingParticipantsWizard participantsPanel;
    private AppointmentRoomWizard bgp;
    private AppointmentStartWindow startPanel;
	
	private Calendar startTime = null;
	private Calendar endTime = null;
	
	public AppointmentWizard(Calendar start, Calendar end){
		startTime = start;
		endTime = end;
		addComponentToPane(this.getContentPane());
		setIconImage(Toolkit.getDefaultToolkit().getImage("resources/icons/aCalendarIcon.png"));
		setTitle("Ny hendelse");
		pack();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		checkState();
		
		roomPicker = new AppointmentsRoomDescription();
		locationPicker = new AppointmentLocationDescription();
		
	}
	
	public AppointmentWizard(){
		setIconImage(Toolkit.getDefaultToolkit().getImage("resources/icons/aCalendarIcon.png"));

		setTitle("Ny hendelse");
		addComponentToPane(this.getContentPane());
		pack();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		checkState();
		
		roomPicker = new AppointmentsRoomDescription();
		locationPicker = new AppointmentLocationDescription();
		
	}
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AppointmentWizard frame = new AppointmentWizard();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}); 	
	}
	
	public void changeRoom(){
	
	}
	
    public void addComponentToPane(Container pane) {
    	
    	// JPanel for buttons; back, next, cancel
    	JPanel buttonPanel = new JPanel();
        Box buttonBox = new Box(BoxLayout.X_AXIS);

        backButton = new JButton("Tilbake");
        nextButton = new JButton("Neste");
        	nextButton.setEnabled(false);
        cancelButton = new JButton("Avbryt");

        backButton.addActionListener(new ButtonActionListener());
        nextButton.addActionListener(new ButtonActionListener());
        cancelButton.addActionListener(new ButtonActionListener());

        buttonPanel.setLayout(new BorderLayout());
        buttonPanel.add(new JSeparator(), BorderLayout.NORTH);

        buttonBox.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10))); 
        buttonBox.add(backButton);
        buttonBox.add(Box.createHorizontalStrut(10));
        buttonBox.add(nextButton);
        buttonBox.add(Box.createHorizontalStrut(30));
        buttonBox.add(cancelButton);
        buttonPanel.add(buttonBox, BorderLayout.EAST);
    	
       
        //Create the "cards".
        
        //Card 1
        startPanel = new AppointmentStartWindow();
        startPanel.getRdbtnAvtale().addActionListener(new ButtonActionListener());
        startPanel.getRdbtnMte().addActionListener(new ButtonActionListener());
        
        //Card 2
        infoPanel = new AppointmentInfoWizard();
        if(startTime != null && endTime != null){
        	String startHour = createNumber(startTime.get(Calendar.HOUR_OF_DAY));
        	String startMinute = createNumber(startTime.get(Calendar.MINUTE));
        	String sTime = startHour + ":" + startMinute;
        	infoPanel.getStartTime().setText(sTime);
        	String endHour = createNumber(endTime.get(Calendar.HOUR_OF_DAY));
        	String endMinute = createNumber(endTime.get(Calendar.MINUTE));
        	String eTime = endHour + ":" + endMinute;
        	infoPanel.getEndTime().setText(eTime);
        	String year = createNumber(startTime.get(Calendar.YEAR));
        	int monthInt = startTime.get(Calendar.MONTH)+1;
        	String month = createNumber(monthInt);
        	String day = createNumber(startTime.get(Calendar.DAY_OF_MONTH));
        	String date = day + "." + month + "." + year;
        	infoPanel.getDate().setText(date);
        }

        //Card 3
        participantsPanel = new MeetingParticipantsWizard(null, true);
       
        //Card 4
        bgp = new AppointmentRoomWizard();
        bgp.getRdbtnLocation().addActionListener(new ButtonActionListener());
        bgp.getRdbtnRoom().addActionListener(new ButtonActionListener());

        //Create the panel that contains the "cards".
        cards = new JPanel(new CardLayout());
        cards.add(startPanel, START);
        cards.add(infoPanel, INFO);
        cards.add(participantsPanel, PARTICIPANTS);
        cards.add(bgp, ROOM);
        
        
        pane.add(buttonPanel, BorderLayout.SOUTH);
        pane.add(cards, BorderLayout.CENTER);
    }
    
    
    public void checkState(){
    	if(currentCard == 1){
    		backButton.setEnabled(false);
    	} else{
    		backButton.setEnabled(true);
    	}
    	if(currentCard == 4){
    		nextButton.setText("Finish");
    	} else{
    		nextButton.setText("Next");
    	}
    }
    
    public class ButtonActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent evt) {
			CardLayout cl = (CardLayout)(cards.getLayout());
			if(evt.getSource().equals(nextButton)){
				if(currentCard < 4){
					if(currentCard == 2 && !isMeeting){
						currentCard += 2;
					}else{
						currentCard += 1;
					}
					if(currentCard == 4) {
						//updates the available rooms list
						if(startTime != null && endTime != null) {
							roomPicker.updateAvailRooms(startTime.getTimeInMillis(), endTime.getTimeInMillis());
						} else {
							JOptionPane.showMessageDialog(null, "Rom kan ikke hentes uten start- og sluttidspunkt");
						}
					}
					cl.show(cards, ""+currentCard);
					pack();
				}
				else if(currentCard == 4){
					String datestart = infoPanel.getStartTime().getText() + ":00 " + infoPanel.getDate().getText();
					String dateend = infoPanel.getEndTime().getText() + ":00 " + infoPanel.getDate().getText();
					Calendar gcStart = TimeSupport.convertStringDateToCalendar(datestart);
					Calendar gcEnd = TimeSupport.convertStringDateToCalendar(dateend);
					
					if(gcStart.getTimeInMillis() > gcEnd.getTimeInMillis() || 
							gcEnd.getTimeInMillis() < gcStart.getTimeInMillis()){
						JOptionPane.showMessageDialog(null, "Ugyldig tidspunkt");
					}else {
						Reservation reservation;
						String location = "";
						String title = infoPanel.getTitle().getText();						//the title of this appointment
						String description = infoPanel.getDescription().getText();			//the description of this appointment
						User owner = Storage.getloggedInUser();	
						List<User> participants;
						if(bgp.getRdbtnRoom().isSelected()){
							Room room = (Room) roomPicker.getRoomList().getSelectedValue();	//the selected room
							reservation = new Reservation(gcStart, gcEnd, room);
						}else{
							reservation = new Reservation(gcStart, gcEnd);
							location = locationPicker.getDescriptionTextArea().getText(); 	//description of this appointment's location
						}
						
						if(startPanel.getRdbtnMte().isSelected()){
							participants = participantsPanel.getParticipantsList();			//list of participants of this meeting
							Meeting meeting = new Meeting(title, description, location, owner, reservation, participants);
							Storage.meetings.add(meeting);
						}else{
							Appointment appointment = new Appointment(title, description, location, owner, reservation);
							Storage.appointments.add(appointment);
						}
						dispose();
					}
				}
				checkState();
			}else if(evt.getSource().equals(backButton)){
				if(currentCard > 1){
					if(currentCard == 4 && !isMeeting){
						currentCard -= 2;
					}else {
						currentCard -= 1;
					}
					cl.show(cards, ""+currentCard);
					pack();
				}
				checkState();
			}else if(evt.getSource().equals(cancelButton)){
				dispose();
			} 
			
			// Statements for Appointment Room Wizard
			if(evt.getSource().equals(bgp.getRdbtnLocation())) {
				if(bgp.isAncestorOf(roomPicker)) bgp.remove(roomPicker);
				bgp.validate();
				bgp.add(locationPicker, BorderLayout.SOUTH);
				bgp.validate();
				
			}
			else if(evt.getSource() == bgp.getRdbtnRoom()){
				if(bgp.isAncestorOf(locationPicker)) bgp.remove(locationPicker);
				bgp.validate();
				bgp.add(roomPicker, BorderLayout.SOUTH);
				bgp.validate();
			}
			
			// Statements for Appointment Start Window
			if(evt.getSource().equals(startPanel.getRdbtnAvtale())){
				isMeeting = false;
				nextButton.setEnabled(true);
			} else if (evt.getSource().equals(startPanel.getRdbtnMte())){
				isMeeting = true;
				nextButton.setEnabled(true);
			}
		}
    	
    }
   public String createNumber(int i){
	   if(i < 10) return "0"+i;
	   else return ""+i;
   }
}

